<?php
namespace app\api\service;

use app\common\model\Setting as SettingModel;
use think\Cache;
use app\common\exception\BaseException;
use app\common\library\sms\Driver as SmsDriver;

class Sms
{
    /**
     * 构建短信类
     * @throws \app\common\exception\BaseException
     * @throws \think\exception\DbException
     */
    private $interval = 900;
    private $driver;
    private $type;
    private $template_code;
    /**
     * 初始化
     * @param $type      发送类型
     * @param $interval  时间间隔
     * @throws \think\Exception
     */
    public function __construct($type,$interval=900)
    {
        $this->type = $type;
        $this->interval = $interval;
        $smsConfig = SettingModel::getItem('sms', '10001');
        $this->driver = new SmsDriver($smsConfig);
        switch ($type){
//            case 'reg':
//                $this->template_code = 'SMS_163455786';
//                break;
            case 'change':
                $this->template_code = 'SMS_163455785';
                break;
            default:
                $this->template_code = 'SMS_163455786';
                break;
        }

    }

    /**
     * @param $mobile 手机号
     * @param $msg   内容
     * @param $type  短信类型
     * @return bool
     * @throws BaseException
     */
    public function sendmsg($mobile,$msg,$type){
        if(empty($mobile)||empty($msg)){
            throw new BaseException(['msg' => '手机号或发送内容为空','code'=>20001]);
            return false;
        }else{
//		    Cache::rm($this->type.$mobile);
            if(Cache::get($this->type.$mobile)){
                throw new BaseException(['msg' => '短信还为失效，请继续使用','code'=>20002]);
                return false;
            }else{
                $code['code'] = $msg;
                // 记录发送缓存
                Cache::set($this->type.$mobile,$msg,$this->interval);
                // 发送短信内容
                if ($this->driver->sendMessages($mobile,$this->template_code,json_encode($code))){
                    return true;
                }else{
                    throw new BaseException(['msg' => '短信发送失败','code'=>20002]);
                    return false;
                }
            }
        }
    }
}